class Task < ActiveRecord::Base
  has_many :periods,
           :include => [:user],
           :order => 'begin_at',
           :dependent => :destroy

  validates_length_of       :title,    :within => 1..100,
                            :too_long => 'タイトルが長すぎます',
                            :too_short => 'タイトルをつけてください'

  validates_presence_of     :begin_at,
                            :message => '開始日時を正しく入力してください'
  validates_presence_of     :end_at,
                            :message => '終了日時を正しく入力してください'


  def users
    return @users if @users

    @users = []
    indexes = {}
    self.periods.each do |period|
      unless indexes[period.user]
        indexes[period.user] = users.size
        @users << [period.user, []]
      end
      @users[indexes[period.user]][1] << period
    end
    @users = @users.sort {|a, b| a[0].display_order <=> b[0].display_order }
  end

  def task
    self
  end

  def formatted_begin_at
    @formatted_begin_at || (self.begin_at.nil? ? '' : self.begin_at.strftime("%Y/%m/%d"))
  end
  def formatted_begin_at=(str)
    @formatted_begin_at = str
    self.begin_at = parse_date(str)
  end

  def formatted_end_at
    @formatted_end_at || (self.end_at.nil? ? '' : self.end_at.strftime("%Y/%m/%d"))
  end
  def formatted_end_at=(str)
    @formatted_end_at = str
    self.end_at = parse_date(str)
  end

  def validate
    if !begin_at.nil? && !end_at.nil?
      if begin_at > end_at
        errors.add(:time, '開始以降の終了日時を指定してください')
      end
    end
  end

  protected

  def after_initialize
    if self.begin_at.nil? && @formatted_begin_at.nil?
        self.begin_at = Time.now.beginning_of_day
    end

    if self.end_at.nil? &&  @formatted_end_at.nil?
      self.end_at = Time.now.beginning_of_day
    end
  end

  def after_validation
    if errors.invalid? :begin_at
      errors.add(:formatted_begin_at, errors.on(:begin_at))
    end
    if errors.invalid? :end_at
      errors.add(:formatted_end_at, errors.on(:end_at))
    end
  end


  private

  def parse_date(formatted)
    begin
      return DateTime.strptime(formatted, "%Y/%m/%d").to_time
    rescue
      return nil
    end
  end
  
end
